import { useRef, useEffect, useState } from "react";
import Play from "./play";

const heros = [] as any;
for (let i = 0; i < 3; i++) {
  heros.push({ id: i + 1, progress: 0, path: "/images/dinosaur1.png" });
}

// 画布标签
let canvasObj = null;
// 画布宽度
let canvas_w = 0;
// 画布长度
let canvas_h = 0;
// 画布对象
let ctx: CanvasRenderingContext2D | any = null;
// 游戏类
let playClass: any = null;
// 当前选择的是第几个
let curr_index = -1;
// 秒钟
let _second=0;

const Battlefield = () => {
  //   const { handleClickOpen } = prop;
  // 我的英雄列表
  const [myHeroList, setMyHeroList] = useState(heros);
  // 当前哪个英雄在更新中
  const [heroIndex, setHeroIndex] = useState(0);
  // 当前选中的英雄
  const [currIndex, setCurrIndex] = useState(-1);
  // 移动坐标
  const [position, setPosition] = useState({ x: 0, y: 0, show: "none" });
  // 拖动的英雄
  const [drawHero, setDrawHero] = useState({ id: -1, path: "" });
  // 英雄拖到哪一列
  const [columnIndex, setColumnIndex] = useState(-1);
  // 进入战场的英雄
  const [battleList, setBattleList] = useState([] as any);

  //   const [progress, setProgress] = useState(0);
  // 影响列表容器
  const heroListRef = useRef(null);

  // 战斗场景英雄开始容器
  const battleFieldRef = useRef(null);

  // 战斗场景英雄开始容器
  const canvasRef = useRef(null);

  /**
   * 设置移动的英雄
   * @param _index
   */
  const setDrawHeroFunc = (_index: number) => {
    const item = myHeroList[_index];
    if (item.progress == 100) {
      setDrawHero({ ...item });
    }
    return item;
  };

  /**
   * 添加英雄
   */
  const addHeroList = (_column: number) => {
    setBattleList(() => [
      ...battleList,
      {
        path: "",
        column: _column,
      },
    ]);
  };

  /**
   * 英雄更新冷却中
   */
  const setMyHeroFunc = () => {
    if (heroIndex < myHeroList.length) {
      setMyHeroList(
        myHeroList.map((item: any, index: number) => {
          if (index == heroIndex) {
            if (item.progress >= 100) {
              setHeroIndex(() => heroIndex + 1);
              return {
                ...item,
                progress: 100,
              };
            } else {
              return {
                ...item,
                progress: item.progress + 0.5,
              };
            }
          } else {
            return item;
          }
        })
      );
    }
  };

  useEffect(() => {
    if (battleFieldRef.current && battleFieldRef.current && canvasRef.current) {
      // 操作DOM元素，例如改变颜色
      const obj = heroListRef.current as any;

      const battleField = battleFieldRef.current as any;
      // 假设有一个元素的id为"myElement"
      const html = document.getElementsByTagName("html") as any;
      // 获取元素的计算后的样式
      const style = window.getComputedStyle(html[0]);
      // 获取字体大小
      const fontSize = parseInt(style.fontSize.replace("px", ""));

      // 窗口宽度
      const window_width = document.documentElement.scrollWidth;
      // 窗口高度
      const window_height = document.documentElement.scrollHeight;
      // 鼠标开始X坐标
      let start_x = 0;
      // 鼠标开始Y坐标
      let start_y = 0;
      // 鼠标移动X坐标
      let move_x = 0;
      // 鼠标移动Y坐标
      let move_y = 0;
      // 差值宽
      let differ_w = 0;
      // 差值高
      let differ_h = 0;

      const clientRect = obj.getBoundingClientRect();
      // 英雄列表容器上边距离
      const start_top = clientRect.top;
      // 英雄列表容器左边距离
      const start_left = clientRect.left;
      // 英雄列表容器宽度
      const start_width = clientRect.width;
      // 英雄列表容器高度
      const start_height = clientRect.height;

      const bfClientRect = battleField.getBoundingClientRect();
      // 战斗场景容器上边距离
      const bf_top = bfClientRect.top;
      // 战斗场景容器左边距离
      const bf_left = bfClientRect.left;
      // 战斗场景容器宽度
      const bf_width = bfClientRect.width;
      // 战斗场景容器高度
      const bf_height = bfClientRect.height;
      // 战斗场景容器分5列，每列宽度
      const bf_column_w = bf_width / 5;

      /**
       * 触摸时的方法
       * @param e
       */
      const handleStart = (e: any) => {
        // console.log(e);
        e.preventDefault();
        start_x = e.touches[0].clientX;
        start_y = e.touches[0].clientY;
        if (
          start_x > start_left &&
          start_x < start_left + start_width &&
          start_y < start_top + start_height &&
          start_y > start_top + start_height - 3 * (start_width + fontSize)
        ) {
          const nums =
            (start_top + start_height - start_y) / (start_width + fontSize);

          const _i = Math.floor(nums);
          differ_w = start_x - start_left;
          differ_h =
            start_y -
            (start_top + start_height - (start_width + fontSize) * (_i + 1));
          const currItem = setDrawHeroFunc(_i);
          if (currItem.progress == 100) {
            curr_index = _i;
          }
        }
      };

      /**
       * 拖动的事件
       * @param e
       */
      const handleMove = (e: any) => {
        // console.log(curr_index);
        if (curr_index !== -1) {
          move_x = e.touches[0].clientX - differ_w;
          move_y = e.touches[0].clientY - differ_h;
          if (move_x > window_width - start_width - 10) {
            move_x = window_width - start_width - 10;
          }
          if (move_x < 0) {
            move_x = 0;
          }
          if (move_y > window_height - fontSize * 6) {
            move_y = window_height - fontSize * 6;
          }
          if (move_y < 0) {
            move_y = 0;
          }
          setPosition({ x: move_x, y: move_y, show: "block" });
        }
      };

      /**
       * 结束的事件
       * @param e
       */
      const handleEnd = (e: any) => {
        if (curr_index !== -1) {
          start_x = e.changedTouches[0].clientX;
          start_y = e.changedTouches[0].clientY;
          if (
            start_x > bf_left &&
            start_x < bf_left + bf_width &&
            start_y > bf_top &&
            start_y < bf_top + bf_height
          ) {
            const _i = Math.floor((start_x - bf_left) / bf_column_w);
            setColumnIndex(_i);
            setCurrIndex(curr_index);
            addHeroList(_i);
          }
          curr_index = -1;

          setPosition({ x: 0, y: 0, show: "none" });
        }
        setCurrIndex(-1);
      };

      // 按下事件
      obj.addEventListener("touchstart", handleStart);

      // 移动事件
      document.addEventListener("touchmove", handleMove);

      // 弹起事件
      window.addEventListener("touchend", handleEnd);

      return () => {
        obj.removeEventListener("touchstart", handleStart);
        document.removeEventListener("touchmove", handleMove);
        window.removeEventListener("touchend", handleEnd);
      };
    }
  }, [heroIndex, currIndex, columnIndex]);

  // 英雄冷却更新
  useEffect(() => {
    // console.log("英雄更新");
    const animate = () => {
      // 执行动画操作
      setMyHeroFunc();
    };

    // 启动动画
    const timer = requestAnimationFrame(animate);

    return () => cancelAnimationFrame(timer);
  }, [myHeroList]);

  // 开始游戏循环
  useEffect(() => {
    if (ctx == null) {
      const canvasBox = canvasRef.current as any;
      const ClientRect = canvasBox.getBoundingClientRect();
      canvasObj = canvasBox.querySelector("canvas");
      canvas_w = ClientRect.width;
      canvas_h = ClientRect.height;
      canvasObj.width = canvas_w;
      canvasObj.height = canvas_h;
      ctx = canvasObj.getContext("2d");
      playClass = new Play(ctx, battleList, setBattleList);
    } else {
      playClass.start();
    }
    
    //
    const animate = () => {
      // 执行动画操作
      if (playClass) {
        _second++;
        if(_second>100){
          ctx.clearRect(0, 0, canvas_w, canvas_h);
          playClass.draw();
          _second=0;
        }
        

        requestAnimationFrame(animate);
      }
      //
    };

    animate();

    // 启动动画
    // const timer = requestAnimationFrame(animate);

    // return () => cancelAnimationFrame(timer);
  }, [battleList]);

  return (
    <div className="game-box">
      {/* 左边 */}
      <div className="side-box left-box">
        <div className="enemy-hero">
          <ul>
            <li>
              <div className="hero-box">
                <img src="/images/dinosaur1.png" alt="" />
                <div className="hero-gray-box" style={{ bottom: "40%" }}>
                  <div className="innder-box">
                    <img src="/images/dinosaur1.png" alt="" />
                  </div>
                </div>
              </div>
            </li>
          </ul>
        </div>
        <div className="centre-box">
          <div className="name">剩余时间</div>
          <div className="val">00:10</div>
        </div>
        <div className="my-hero">
          {/* 移动框 */}
          <div
            className="move-box"
            style={{
              left: position.x + "px",
              top: position.y + "px",
              display: position.show,
            }}
          >
            <img src={drawHero.path} />
          </div>
          <ul className="here-list" ref={heroListRef}>
            {myHeroList.map((item: any) => (
              <li key={item.id}>
                <div
                  className={
                    item.progress == 100 ? "hero-box finish" : "hero-box"
                  }
                >
                  <img src={item.path} alt="" />
                  <div
                    className="hero-gray-box"
                    style={{
                      bottom: item.progress,
                    }}
                  >
                    <div className="innder-box">
                      <img src={item.path} alt="" />
                    </div>
                  </div>
                </div>
              </li>
            ))}
          </ul>
        </div>
      </div>
      {/* 右边 */}
      <div className="side-box right-box">
        <div className="enemy-hero">
          <ul>
            <li>
              <div className="skill-box">
                <img src="/images/skill_icon.png" alt="" />
              </div>
            </li>
          </ul>
        </div>
        <div className="centre-box">
          <div className="name">托管</div>
          <div className="val">1000</div>
          <div className="unit">TON</div>
        </div>
        <div className="my-hero">
          <ul>
            <li>
              <div className="skill-box">
                <img src="/images/skill_icon.png" alt="" />
              </div>
            </li>
          </ul>
        </div>
      </div>
      {/* 战斗中心 */}
      <div className="ballte-box">
        <div className="canvas-box" ref={canvasRef}>
          <canvas className="canvas-obj"></canvas>
        </div>
        <div className="start-list-box" ref={battleFieldRef}>
          <div className="put-box"></div>
          <div className="put-box"></div>
          <div className="put-box"></div>
          <div className="put-box"></div>
          <div className="put-box"></div>
        </div>
      </div>
    </div>
  );
};

export default Battlefield;
